/**
 * FamilyChain HTTP 请求封装
 */

import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios'
import { API_BASE_URL, REQUEST_TIMEOUT } from './config'

// 创建 axios 实例
const request: AxiosInstance = axios.create({
  baseURL: API_BASE_URL,
  timeout: REQUEST_TIMEOUT,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // 从 localStorage 获取 token
    const token = localStorage.getItem('familychain_token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    // 添加时间戳防止缓存
    if (config.method === 'get') {
      config.params = {
        ...config.params,
        _t: Date.now(),
      }
    }
    
    console.log('🚀 API Request:', config.method?.toUpperCase(), config.url, config.data || config.params)
    return config
  },
  (error) => {
    console.error('❌ Request Error:', error)
    return Promise.reject(error)
  },
)

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    console.log('✅ API Response:', response.config.url, response.data)
    
    // 如果后端返回的数据格式为 { code, data, message }
    const { data } = response
    if (data && typeof data === 'object' && 'code' in data) {
      if (data.code === 0 || data.code === 200) {
        return data.data || data
      } else {
        console.error('❌ API Error:', data.message || '请求失败')
        return Promise.reject(new Error(data.message || '请求失败'))
      }
    }
    
    // 直接返回数据
    return data
  },
  (error) => {
    console.error('❌ Response Error:', error.response?.data || error.message)
    
    // 处理不同的错误状态码
    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 401:
          // 未授权，清除 token 并跳转到登录页
          localStorage.removeItem('familychain_token')
          window.location.href = '/login'
          break
        case 403:
          console.error('❌ 无权限访问')
          break
        case 404:
          console.error('❌ 请求的资源不存在')
          break
        case 500:
          console.error('❌ 服务器错误')
          break
        default:
          console.error(`❌ 请求失败: ${status}`)
      }
      
      return Promise.reject(data || error)
    }
    
    // 网络错误或超时
    if (error.message.includes('timeout')) {
      console.error('❌ 请求超时')
    } else if (error.message.includes('Network Error')) {
      console.error('❌ 网络错误，请检查网络连接')
    }
    
    return Promise.reject(error)
  },
)

// 导出请求方法
export const http = {
  get: <T = any>(url: string, config?: AxiosRequestConfig): Promise<T> =>
    request.get(url, config),
  
  post: <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> =>
    request.post(url, data, config),
  
  put: <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> =>
    request.put(url, data, config),
  
  delete: <T = any>(url: string, config?: AxiosRequestConfig): Promise<T> =>
    request.delete(url, config),
  
  patch: <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> =>
    request.patch(url, data, config),
}

export default request

